/*
 * Copyright (c) 2013, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.syncomponents.convert.sample;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.syncomponents.convert.AbstractHttpMessageConvert;
import com.syncomponents.convert.MessageConvertContainerImpl;
import com.syncomponents.convert.MessageConvertHandler;
import com.syncomponents.convert.PlatformType;
import com.syncomponents.core.MessageConstant;
import com.syncomponents.remoting.message.HttpMessageRequest;
import com.syncomponents.support.HttpResourceBean;
import com.syncomponents.support.ITarget;
import com.syncomponents.support.ResourceBean;

import commonj.sdo.DataObject;

/**
 * 
 * @author sunkey
 * @date Jan 16, 2014
 */
@Component(value = "sampleConvert")
public class SampleMessageConvert extends AbstractHttpMessageConvert {

    @Resource
    private SampleRequestResource sampleRequestResource;

    @Resource
    private MessageConvertHandler xsltConvertHandler;

    @Resource
    private MessageConvertContainerImpl messageConvertContainer;
    
    @Resource
    private ITarget sampleTarget;

    @Override
    public HttpMessageRequest getMessageRequest(DataObject dobj, String msg) {
        HttpMessageRequest messageRequest = new HttpMessageRequest();

        String action = dobj.getString(MessageConstant.MESSAGE_ACTION);
        HttpResourceBean resource = sampleRequestResource.getResource(action);
        
        messageRequest.setMethod(resource.getHttpMethod());
        messageRequest.setUrl(resource.getUrl());

        messageRequest.setMsgBody(xsltConvertHandler.handle(msg, resource.getXlstReqPath(), null));

        return messageRequest;
    }

    @Override
    public Object getResponse(DataObject dobj, String msg) {

        String action = dobj.getString(MessageConstant.MESSAGE_ACTION);
        ResourceBean resource = sampleRequestResource.getResource(action);

        // Map<String, Object> paramMap = new HashMap<String, Object>();
        // paramMap.put(MessageConstant.MESSAGE_ACTION, dobj.getString(MessageConstant.MESSAGE_ACTION));
        // paramMap.put(MessageConstant.MESSAGE_TYPE, dobj.getString(MessageConstant.MESSAGE_TYPE));
        //
        
        //TODO 如果api token是个临时的，这里需要处理返回失败时，重新申请token
        
        return xsltConvertHandler.handle(msg, resource.getXlstRespPath(), null);
    }

    @Override
    public ITarget getTarget() {
        return sampleTarget;
    }

    @Override
    public MessageConvertContainerImpl getMessageConvertContainer() {
        return messageConvertContainer;
    }

    @Override
    public PlatformType getPlatformType() {
        return PlatformType.SAMPLE;
    }

}
